package com.boyunv.decorator.example02;/*
 *@description
 *  具体装饰者类,---对文件内容进行 加密和解密
 *@author boyunv
 *@create 2023/7/16 8:54
 *@version 1.0
 */

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class EncryptionDecorator extends DataLoaderDecorator{

    public EncryptionDecorator(DataLoader dataLoader) {
        super(dataLoader);
    }

    @Override
    public String read() {


        return decode(super.read());
    }

    @Override
    public void write(String data) {
        super.write(encode(data));
    }


    //加密操作
    public String  encode(String data){

        try {
            Base64.Encoder encoder = Base64.getEncoder();
            //数据转换成字节符
            byte[] bytes = data.getBytes("utf-8");
            String result = encoder.encodeToString(bytes);

            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //解密
    public String  decode(String data){

        try {
            Base64.Decoder decoder = Base64.getDecoder();
            String res = new String(decoder.decode(data), "utf-8");

            return res;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
